<script lang="ts" setup>
import { type FormInstance, Message } from '@arco-design/web-vue'
import CouponTemplateSelect from './components/CouponTemplateSelect.vue'
import { useForm } from '@/hooks'
import { CouponApi, ParentApi } from '@/apis'

const emit = defineEmits(['ok'])
const { form, resetForm } = useForm<CouponApi.CouponDistributeReq>({
  couponTemplateId: '',
  parentId: '',
})

const rules: FormInstance['rules'] = {
  couponTemplateId: [{ required: true, message: '请选择优惠券' }],
  parentId: [{ required: true, message: '请选择家长' }],
}

const formRef = ref<FormInstance>()
const visible = ref(false)

// 家长
const parentList = ref<ParentApi.ParentResp[]>([])
const loading = ref(false)

const getParentList = async (keyword: string = '') => {
  try {
    loading.value = true
    const res = await ParentApi.getParentPage({
      keyword,
      page: 1,
      size: 15,
    })
    parentList.value = res.records || []
  } finally {
    loading.value = false
  }
}

const commit = async () => {
  try {
    await CouponApi.distributeCoupon(form)
    Message.success('添加成功')
    return true
  // eslint-disable-next-line unused-imports/no-unused-vars
  } catch (_) {
    return false
  }
}

const beforeOk = async () => {
  const val = await formRef.value?.validate()
  if (val) {
    return false
  }
  return await commit()
}
const handleOk = () => {
  emit('ok')
}

const reset = () => {
  formRef.value?.clearValidate()
  resetForm()
}

const handleCancel = () => {
  visible.value = false
}

const open = () => {
  reset()
  visible.value = true
}

onMounted(() => {
  getParentList()
})

defineExpose({
  open,
})
</script>

<template>
  <a-modal v-model:visible="visible" width="600px" :on-before-ok="beforeOk" @ok="handleOk" @cancel="handleCancel">
    <template #title>
      优惠券发放
    </template>
    <a-form ref="formRef" :rules="rules" :model="form">
      <a-form-item label="优惠券" field="couponTemplateId">
        <CouponTemplateSelect v-model="form.couponTemplateId" />
      </a-form-item>
      <a-form-item label="领券家长" field="parentId">
        <a-select
          v-model="form.parentId" placeholder="请选择领券家长（输入关键字搜索）" :field-names="{ label: 'name', value: 'id' }" :options="parentList" :loading="loading"
          allow-search :filter-option="false" :show-extra-options="false" @search="getParentList"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<style lang="less" scoped>

</style>
